//
//  InitViewController.m
//  ICard
//
//  Created by fanshao on 11-2-25.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "InitViewController.h"
#import "constant.h"
#import "CardViewController.h"
#import "NSString+SBJSON.h"
#import "LogInViewController.h"
#import "UserInfo.h"


@implementation InitViewController
@synthesize showInfoLabel;
@synthesize receivedData;

// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	/*if ([[NSUserDefaults standardUserDefaults]  ) {
		<#statements#>
	}*/
    [super viewDidLoad];
	canClick = YES;
	[self setTitle:@"爱宾卡片"];
	KDActivityView *tView = [[KDActivityView alloc] initWithFrame:CGRectMake(60, 100, 200, 100)];
	activityView = tView;

}

-(void)addProgressIndicator {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    [self.view addSubview:activityView];
    activityView.alpha = 0.0;
	//activityView.transform = CGAffineTransformMakeRotation(M_PI * (90.0 / 180.0));
	activityView.center = CGPointMake(160, 240);
    [self.view bringSubviewToFront:activityView];
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationTransition:UIViewAnimationTransitionNone forView:self.view cache:YES];
    activityView.alpha = 0.7;
    [UIView commitAnimations];
    [pool release];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)showProgressIndicator{
	[activityView setHidden:NO];
}
- (void)removeProgressIndicator{
	[activityView removeFromSuperview];
}

- (IBAction) newCard{
	if (!canClick) {
		return;
	}
	canClick  = NO;
	curConnectFlag = 2;
	[self addProgressIndicator];
	[self loginWithAnonymous];
	
}

- (IBAction)loginwith{
	if (!canClick) {
		return;
	}
	//canClick  = NO;
	//curConnectFlag = 3;
	LogInViewController *cardViewController = [[LogInViewController alloc] init];
	
	if(cardViewController == nil)
		return;
	else
	{
		[cardViewController setTitle:@"登录"];
		[[self navigationController] pushViewController:cardViewController animated:YES];
		
	}
	[cardViewController release];
	
}

- (void)loginWithAnonymous{
	self.receivedData = [NSMutableData data];
	//}
	NSString *mnc = @"00";
	NSString *mcc = @"460";
	
	NSString *requestStirng =[NSString stringWithFormat: @"mnc=%@&mcc=%@", mnc, mcc];
	NSData *postData = [NSData dataWithBytes:[requestStirng UTF8String] length:[requestStirng length]];
	
	
	
	NSMutableURLRequest *connectionRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[KAnonymousLoginURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
	[connectionRequest setHTTPMethod:@"POST"];
	[connectionRequest setTimeoutInterval:10.0f];
	[connectionRequest setCachePolicy:NSURLRequestUseProtocolCachePolicy];
	[connectionRequest setHTTPBody:postData];
	
	NSURLConnection *connection = [[NSURLConnection alloc]
								   initWithRequest:connectionRequest
								   delegate:self];
	[connection autorelease];
	
}
- (IBAction) AnonymousLogin{
	if (!canClick) {
		return;
	}
	canClick  = NO;
	curConnectFlag = 1;
	[self loginWithAnonymous];
}

#pragma mark connection delegate
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
	
	[self.receivedData appendData:data];
	NSLog(@"self.reveivedData is %@", self.receivedData);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
	
	NSString *temp = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding] ;
	NSLog(@"temp is %@", temp);

	canClick  = YES;
	[self removeProgressIndicator];
	if (curConnectFlag == 1) {
		NSNumber *number =  [[temp JSONValue]  valueForKey:@"rlt"] ;
		
		
		int ret = [number intValue];
		if (ret) {
			NSString *errorInfo = [[temp JSONValue] valueForKey:@"txt"];
			NSLog(@"errorInfo is %@",errorInfo);
			UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert" ,nil) message:NSLocalizedString(@"Can't log in!", nil)
															   delegate:nil cancelButtonTitle:NSLocalizedString(@"Close",nil) otherButtonTitles:nil];
			
			[alerView show];
			[alerView release];
			
		}
		else {
			NSString *ppt = [[temp JSONValue] valueForKey:@"ppt"];
			[[UserInfo shardUserInfo] setPpt:ppt];
			
		}
		
	}
	else if (curConnectFlag == 2){
		NSNumber *number =  [[temp JSONValue]  valueForKey:@"rlt"] ;
		
		int ret = [number intValue];
		if (ret) {
			NSString *errorInfo = [[temp JSONValue] valueForKey:@"txt"];
			NSLog(@"errorInfo is %@",errorInfo);
			UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert" ,nil) message:NSLocalizedString(@"Can't log in!", nil)
															   delegate:nil cancelButtonTitle:NSLocalizedString(@"Close",nil) otherButtonTitles:nil];
			
			[alerView show];
			[alerView release];
			
		}
		else {
			NSString *ppt = [[temp JSONValue] valueForKey:@"ppt"];
			[[UserInfo shardUserInfo] setPpt:ppt];
			[[UserInfo shardUserInfo] savePref];
			CardViewController *cardViewController = [[CardViewController alloc] init];
			
			if(cardViewController == nil)
				return;
			else
			{
				[cardViewController setTitle:@"新建名片"];
				[[self navigationController] pushViewController:cardViewController animated:YES];
				
			}
			[cardViewController release];
		}
		
	}
	else if (curConnectFlag == 3){
		
	}

	
}
- (void)didFailDownloadWithError:(NSError *)error {
	//[self stopAnimating];
	//[self processError:error];
	NSString *str = [error localizedDescription];
	UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert" ,nil) message:str
													   delegate:nil cancelButtonTitle:NSLocalizedString(@"Close",nil) otherButtonTitles:nil];
	
	[alerView show];
	[alerView release];
	canClick = YES;
	[self removeProgressIndicator];
	
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	[self didFailDownloadWithError:error];
	
	
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
	BOOL disconnect = NO;
	NSLog(@"Response, the statuscode is %d", [(NSHTTPURLResponse *)response statusCode]);	//[self setResponse:response];
	
	switch([(NSHTTPURLResponse *)response statusCode]) {
		case 200:
		case 206:
			break;
		case 304:
			disconnect = YES;
			break;
		case 400:
		{
			UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert" ,nil) message:NSLocalizedString(@"Can't get the Chinese name", nil)
															   delegate:nil cancelButtonTitle:NSLocalizedString(@"Close",nil) otherButtonTitles:nil];
			
			[alerView show];
			[alerView release];
			disconnect = YES;
		}
			break;
			
			break;
			
		case 404:
		{
			UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert" ,nil) message:NSLocalizedString(@"Can't get the Chinese name", nil)
															   delegate:nil cancelButtonTitle:NSLocalizedString(@"Close",nil) otherButtonTitles:nil];
			
			[alerView show];
			[alerView release];
			
			//[self connection:connection didFailWithError:theError];
			//[self stopAnimating];
			
			disconnect = YES;
		}
			break;
		case 416:
		{
			NSError *theError = [NSError errorWithDomain:@"CustomDomain"
													code:416 
												userInfo:[NSDictionary dictionaryWithObject:@"Range is missmatch."
																					 forKey:NSLocalizedFailureReasonErrorKey]];
			[self connection:connection didFailWithError:theError];
			disconnect = YES;
		}
			break;
		case 403:
		case 401:
		case 500:
		{
			UIAlertView *alerView =  [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert" ,nil) message:NSLocalizedString(@"Server error Name Get", nil)
															   delegate:nil cancelButtonTitle:NSLocalizedString(@"Close",nil) otherButtonTitles:nil];
			
			[alerView show];
			[alerView release];
			//[self stopAnimating];
		}
			break;
		default:
		{
			NSError *theError = [NSError errorWithDomain:@"CustomDomain"
													code:666
												userInfo:[NSDictionary dictionaryWithObject:@"Unknown error."
																					 forKey:NSLocalizedFailureReasonErrorKey]];
			[self connection:connection didFailWithError:theError];
		}
			disconnect = YES;
			break;
	}
	
}

- (void)dealloc {
	
	[showInfoLabel release];
    [super dealloc];
}


@end
